/*
 * Thread Demos
 * Spring 2013 TCSS 558
 * Daniel M. Zimmerman
 */

package threads;

/**
 * Creates a specified number of threads, each assigned a number,
 * and prints two lines for each to standard output.
 * 
 * @author Daniel M. Zimmerman
 * @version Spring 2013
 */
public class NumberLines implements Runnable
{
  // Static Fields
  
  /**
   * The prefix for each outputted line.
   */
  public static final String OUTPUT_PREFIX = "I am thread number ";
  
  /**
   * The default number of threads. 
   */
  public static final int DEFAULT_NUM_THREADS = 27;
  
  // Instance Fields
  
  /** 
   * The number corresponding to this thread.
   */
  private final int my_number;

  // Constructor
  
  /**
   * Constructs a thread with the specified number.
   * 
   * @param the_number The number.
   */
  public NumberLines(final int the_number)
  { 
    my_number = the_number; 
  }

  // Instance Methods
  
  /**
   * Runs the thread, by having it print its identification 
   * information twice. 
   */
  public void run()
  {
    System.out.print(OUTPUT_PREFIX + my_number);
    System.out.println();
    try
    {
      Thread.sleep(10000);
    }
    catch (final InterruptedException e)
    {
      
    }
    System.err.print(OUTPUT_PREFIX + my_number);
    System.err.println();
  }
  
  // Main Method
  
  /**
   * Creates a specified number of threads (or the default, if none
   * is specified) and runs them.
   * 
   * @param the_args Command line arguments; argument 0, if present and
   * an integer, is the number of threads to create.
   */
  public static void main(final String... the_args)
  {
    int num_threads = DEFAULT_NUM_THREADS;
    
    if (the_args.length > 0)
    {
      try
      {
        num_threads = Integer.parseInt(the_args[0]);
      }
      catch (final NumberFormatException e)
      {
        num_threads = DEFAULT_NUM_THREADS;
      }
    }
    
    final Thread[] threads = new Thread[num_threads];
    
    for (int i = 0; i < num_threads; i++)
    {
      threads[i] = new Thread(new NumberLines(i));
      // to make the threads daemon threads, uncomment the line below
      threads[i].setDaemon(true);
    }

    for (int i = 0; i < num_threads; i++)
    {
      threads[i].start();
    }
  }
}
